Assembly Language

Fibonacci

For the Little Computer 3

In [1]:
.ORIG x3000 
        LD R3, N_VAL
Loop    BRz Done ; check if last operation flagged z-bit
        LD R0, I_VAL ; load i
        LD R1, J_VAL ; load j

        ADD R2, R0, R1 ; t = i + j

        ST R1, I_VAL ; j = i (R1)
        ST R2, J_VAL ; j = t (R2)

        ADD R3, R3, -1 ; count down n
        BR Loop

Done    ST R2, RESULT ; Result in R2
 
        HALT
RESULT  .FILL x0000 
I_VAL   .FILL x0001
J_VAL   .FILL x0000
N_VAL   .FILL 20 ; n -> fib(n) fib(20) = #6765  = x1A6D
        .END
============================================================
Memory disassembled:
============================================================
           x3000: x260D  LD R3, N_VAL                              [line: 1]
LOOP:      x3001: x0407  BRz DONE (or 7)                           [line: 2]
           x3002: x2009  LD R0, I_VAL                              [line: 3]
           x3003: x2209  LD R1, J_VAL                              [line: 4]
           x3004: x1401  ADD R2, R0, R1                            [line: 6]
           x3005: x3206  ST R1, I_VAL                              [line: 8]
           x3006: x3406  ST R2, J_VAL                              [line: 9]
           x3007: x16FF  ADD R3, R3, #-1                           [line: 11]
           x3008: x0FF8  BRnzp LOOP                                [line: 12]
DONE:      x3009: x3401  ST R2, RESULT                             [line: 14]
           x300A: xF025  HALT                                      [line: 16]
RESULT:    x300B: x0000  NOOP - (no BR to I_VAL) (or 0)            [line: 17]
I_VAL:     x300C: x0001  NOOP - (no BR to N_VAL) (or 1)            [line: 18]
J_VAL:     x300D: x0000  NOOP - (no BR to N_VAL) (or 0)            [line: 19]
N_VAL:     x300E: x0014  NOOP - (no BR to x3023) (or 20)           [line: 20]

============================================================
Registers:
============================================================
PC: x300F
N: 0 Z: 1 P: 0 
R0: x0000 R1: x0000 R2: x0000 R3: x0000 
R4: x0000 R5: x0000 R6: x0000 R7: x0000 
In [2]:
%exe
============================================================
Computation completed
============================================================
Instructions: 164
Cycles: 1274 (0.000637 milliseconds)

============================================================
Registers:
============================================================
PC: x048E
N: 0 Z: 1 P: 0 
R0: x0A18 R1: x1055 R2: x1A6D R3: x0000 
R4: x0000 R5: x0000 R6: x0000 R7: x300B 
In [4]:
%%python

print(0x1A6D)

def fib(n):
    if n < 3:
        return 1
    else:
        return fib(n - 1) + fib(n - 2)
    
print(fib(20))
6765
6765